package com.android.pagemarket.business.logic;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.database.sqlite.SQLiteException;
import android.os.AsyncTask;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.android.pagemarket.MyApplication;
import com.android.pagemarket.business.model.QuotType;
import com.android.pagemarket.business.model.Region;
import com.android.pagemarket.business.model.VersionInfo;
import com.android.pagemarket.io.database.DB;
import com.android.pagemarket.io.protocol.HttpManager;
import com.android.pagemarket.io.protocol.in.HttpAction;
import com.android.pagemarket.io.protocol.in.HttpAction.ActionListener;
import com.android.pagemarket.io.protocol.in.InitAction;
import com.android.pagemarket.io.protocol.in.LoginAction;
import com.android.pagemarket.io.protocol.out.Company;
import com.android.pagemarket.io.protocol.out.InitInfo;
import com.android.pagemarket.ui.adapter.AreaArrayAdapter;
import com.android.pagemarket.util.NotifyListener;
import com.j256.ormlite.dao.Dao;

/*********************************************************
 * @author : zhaohua
 * @version : 2012-11-7
 * @see : 初始化管理器，包括初始化信息，即各个版本代码的管理
 * @Copyright : copyrights reserved by personal 2007-2011
 **********************************************************/
public class InitManager extends BaseManager
{
    public static SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    private InitInfo mInitInfo;
    private VersionInfo mVersionInfo;
    public  Company mLoginCompany;
    
    private Dao<InitInfo, Integer> mInitInfoDao;
    private Dao<VersionInfo, Integer> mVersionInfoDao;
    private Dao<QuotType, Integer> mQuotDao;
    private Dao<Region, Integer> mRegionDao;
    
    private String mImieStr;
    /////////////////////////////////////////////////////////////////////////////
    private InitManager()
    {
        mInitInfoDao = DB.getDatabaseHelper().getInitInfoDao();
        mVersionInfoDao = DB.getDatabaseHelper().getVersionInfoDao();
        mQuotDao = DB.getDatabaseHelper().getQuotDao();
        mRegionDao = DB.getDatabaseHelper().getRegionDao();
    }
    private static InitManager instance;
    public static InitManager getInstance()
    {
        if(instance == null)
        {
            instance = new InitManager();
        }
        return instance;
    }
    
    @Override
    public void init()
    {
        HttpManager.getInstance().addHeader("uid", getImei());
        doInit(null);
    }

    @Override
    public void destory()
    {
        mInitInfo = null;
        mVersionInfo = null;
        mLoginCompany = null;
    }
    /////////////////////////////////////////////////////////////////////////////
    public void autoLogin()
    {
        if(mLoginCompany != null) return;
        
        String name = MyApplication.getContext().getLastLoginName();
        String num  = MyApplication.getContext().getLastLoginNum();
        if(name == null || num == null) return;
        
        LoginAction action = new LoginAction(name, num);
        action.setActionListener(new ActionListener<Company>()
        {
            @Override
            public void onSucceed(Company result)
            {
                if(result.isNoError())
                {
                    InitManager.getInstance().onLogin(result);
                    Log.d("auto login", " auto login OK!");
                }else
                {
                    Log.e("auto login", " auto login fail:" + result.resultInfo);
                }
            }
            @Override
            public void onError(int resultCode)
            {
                Log.e("auto login", " auto login fail!");
            }
        });
        action.submit();
    }
    
    public void onLogin(Company com)
    {
        mLoginCompany = com;
        if(com != null)
        {
            MyApplication.getContext().setLastLogin(mLoginCompany.companyName, mLoginCompany.companyNum);
        }else
        {
            MyApplication.getContext().setLastLogin(null, null); 
        }
    }
    
    public boolean isLogin()
    {
        return mLoginCompany != null;
    }
    
    public boolean isInitOK()
    {
        return mInitInfo != null;
    }
    
    public int getAlertVersion()
    {
        return mVersionInfo.alertsVersion;
    }
    
    public int getPromotVersion()
    {
        return mVersionInfo.promotVersion;
    }
    
    public void updateAlertVersion(int version)
    {
        if(mVersionInfo.alertsVersion >= version) return;
        mVersionInfo.alertsVersion = version;
        new AsyncTask<Void, Void, Void>()
        {
            @Override
            protected Void doInBackground(Void... params)
            {            
                try
                {
                     mVersionInfoDao.update(mVersionInfo);
                } catch (SQLException e)
                {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute();
        return;
    }
    
    public void updatePromotVersion(int version)
    {
        if(mVersionInfo.promotVersion >= version) return;
        mVersionInfo.promotVersion = version;
        new AsyncTask<Void, Void, Void>()
        {
            @Override
            protected Void doInBackground(Void... params)
            {
                try
                {
                    mVersionInfoDao.update(mVersionInfo);
                } catch (SQLException e)
                {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute();
        return;
    }
    
    public void updateLastQutoDateTime(long time)
    {
        if(mVersionInfo == null || time == 0) return; 
        mVersionInfo.lastQutoDateTime = formater.format(new Date(time));        
        new AsyncTask<Void, Void, Void>()
        {
            @Override
            protected Void doInBackground(Void... params)
            {
                try
                {
                    mVersionInfoDao.update(mVersionInfo);
                } catch (SQLException e)
                {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute();
        return;
    }
    
    public void updateLastLeaveTime(long time)
    {
        if(mVersionInfo == null || time == 0) return;
        mVersionInfo.lastLeaveTime = formater.format(new Date(time));        
        new AsyncTask<Void, Void, Void>()
        {
            @Override
            protected Void doInBackground(Void... params)
            {
                try
                {
                    mVersionInfoDao.update(mVersionInfo);
                } catch (SQLException e)
                {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute();
        return;
    }
    
    public String getLastQutoDateTime()
    {
        if(mVersionInfo == null || mVersionInfo.lastQutoDateTime == null)
        {
            return formater.format(new Date());
        }else
        {
            return mVersionInfo.lastQutoDateTime;
        }
    }
    
    public String getLastLeaveTime()
    {
        if(mVersionInfo == null || mVersionInfo.lastLeaveTime == null)
        {
            return formater.format(new Date());
        }else
        {
            return mVersionInfo.lastLeaveTime;
        }
    }
    
    @SuppressWarnings("unchecked")
    public boolean initRegionAdapter(AreaArrayAdapter<Region> adapter)
    {
        if(mInitInfo != null)
        {
            for(Region one : mInitInfo.regionList)
            {
                adapter.add(one);
            }
            return true;
        }
        return false;
    }
    
    @SuppressWarnings("unchecked")
    public boolean initQuotTypeAdapter(AreaArrayAdapter<QuotType> adapter)
    {
        if(mInitInfo != null)
        {
            for(QuotType one : mInitInfo.quotList)
            {
                adapter.add(one);
            }
            return true;
        }
        return false;
    }
    
    public int getLoginRegionPosition()
    {
        if(mInitInfo != null && mLoginCompany != null)
        {
            int i = 0;
            for(Region one : mInitInfo.regionList)
            {
                if(mLoginCompany.regionName.equals(one.regionName))
                {
                    return i;
                }
                i++;
            }
            return 0;
        }
        return -1;
    }
    
    public int getLoginQuotTypePosition()
    {
        if(mInitInfo != null && mLoginCompany != null && mLoginCompany.offerType != null)
        {
            int i = 0;
            for(QuotType one : mInitInfo.quotList)
            {
                if(mLoginCompany.offerType.equals(one.quotName))
                {
                    return i;
                }
                i++;
            }
            return 0;
        }
        return -1;
    }
    
    public String getServerPhone()
    {
        return mInitInfo != null ? mInitInfo.serverCall : null;
    }
    
    // 获取报价电话，如果登录的话，就返回登录用户的报价电话，否则就返回默认的报价电话
    public String getOfferPhone()
    {
        if(mLoginCompany != null && mLoginCompany.offerCall != null)
        {
            return mLoginCompany.offerCall;
        }else
        {
            return mInitInfo != null ? mInitInfo.offerCall : null;
        }
    }
    
    public String getAboutPhone()
    {
        return mInitInfo != null ? mInitInfo.aboutCall : null;
    }
    
    public String getPushUrl()
    {
        if(mInitInfo != null && mInitInfo.pushURL != null)
        {
            return mInitInfo.pushURL;
        }else
        {
            return null;
        }
    }
    
    public String getImei()
    {
        if(mImieStr == null)
        {
            TelephonyManager telephonyManager=(TelephonyManager) MyApplication.getContext().getSystemService(Context.TELEPHONY_SERVICE);
            String imei=telephonyManager.getDeviceId();
            if(imei == null)
            {
                imei = "none";
            }
            String androidId = Secure.getString(MyApplication.getContext().getContentResolver(), Secure.ANDROID_ID);
            mImieStr = imei + "_" + androidId;
        }
        return mImieStr;
    }
    
    private void setInifInfo(InitInfo result)
    {
        mInitInfo = result;
        ContentManager.getInstance().init();
    }
    
    public void doInit(final NotifyListener<Boolean> listnener)
    {
        new AsyncTask<Void, Void, Void>()
        {
            @Override
            protected Void doInBackground(Void... params)
            {
                try
                {
                    List<VersionInfo> versions = mVersionInfoDao.queryForAll();
                    if(versions != null && versions.size() > 0)
                    {
                        mVersionInfo = versions.get(0);
                    }else
                    {
                        mVersionInfo = new VersionInfo();
                        mVersionInfoDao.create(mVersionInfo);
                    }
                    
                    InitAction action = new InitAction(mVersionInfo.initVersion);
                    action.setActionListener(new ActionListener<InitInfo>()
                    {
                        @Override
                        public void onSucceed(InitInfo result)
                        {
                            if(result.isNoError())
                            {
                                // 有更新             
                                updateInitInfo(result);
                                if(listnener != null)
                                {
                                    listnener.onSucceed(true);
                                }
                            }else
                            {
                                // 没有
                                initFromDB(listnener);
                            }
                        }

                        @Override
                        public void onError(int resultCode)
                        {
                            initFromDB(listnener);
                        }
                    });
                    HttpManager.getInstance().submitAction(action);
                } catch (SQLException e)
                {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute();
    }
    
    // 数据库获取初始化信息
    private void initFromDB(final NotifyListener<Boolean> listener)
    {
        new AsyncTask<Void, Void, Boolean>()
        {
            @Override
            protected Boolean doInBackground(Void... params)
            {
                try
                {
                    List<InitInfo> list = mInitInfoDao.queryForAll();
                    if(list != null && list.size() > 0)
                    {
                        setInifInfo(list.get(0));
                        mInitInfo.toList();                       
                        return true;
                    }
                } catch (SQLException e)
                {
                    e.printStackTrace();
                }
                return false;
            }
            
            protected void onPostExecute(Boolean result) 
            {
                if(listener != null)
                {
                    if(result)
                    {
                        listener.onSucceed(true);
                    }else
                    {
                        listener.onError(HttpAction.ERR_NETWORK);
                    }
                }
            };
        }.execute();
    }
    // 更新初始化信息到数据库
    private void updateInitInfo(InitInfo result)
    {
        setInifInfo(result);
        
        new AsyncTask<Void, Void, Void>()
        {
            @Override
            protected Void doInBackground(Void... params)
            {
                try
                {                    
                    mInitInfoDao.deleteById(mVersionInfo.initVersion);
                    mVersionInfo.initVersion = mInitInfo.initNo;
                    mVersionInfoDao.update(mVersionInfo);
                    // TODO ...
                    mInitInfoDao.create(mInitInfo);
                    if(mInitInfo.quotList != null && mInitInfo.quotList.size() > 0)
                    {
                        for(QuotType one : mInitInfo.quotList)
                        {
                            try {
                                mQuotDao.create(one);
                            }catch(SQLiteException e)
                            {
                                e.printStackTrace();
                            }
                        }
                    }
                    if(mInitInfo.regionList != null && mInitInfo.regionList.size() > 0)
                    {
                        for(Region one : mInitInfo.regionList)
                        {
                            try {
                                mRegionDao.create(one);
                            }catch(SQLiteException e)
                            {
                                e.printStackTrace();
                            }
                        }
                    }
                } catch (SQLException e)
                {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute();
    }
}
